package cn.e2win.biz.base;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import cn.e2win.base.controller.MyException;
import cn.e2win.base.entity.SysAttach;
import cn.e2win.base.entity.SysLabel;
import cn.e2win.base.entity.SysLabelSet;
import cn.e2win.base.json.vo.Result;
import cn.e2win.biz.comm.ViewExcel;
import cn.e2win.biz.dbo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.e2win.base.json.vo.Pager;
import cn.e2win.biz.annotation.PageParam;
import org.springframework.web.servlet.ModelAndView;


@Controller
@Scope("request")
@RequestMapping("/common")
public class CommonController extends BaseController {

	@Autowired
	private CommonService commonService;
	
	@Override
	public BaseService initService() {
		return commonService;
	}

	@RequestMapping("labelPager")
	public String labelPager(HttpServletRequest request, ModelMap modelMap){
		commonService.pagerLabel(pager);
		modelMap.put("pager", pager);
		return "comm/labelPager";
	}

	@RequestMapping("labelPagerExcel")
	public ModelAndView customerPagerExcel(HttpServletRequest request, ModelMap modelMap) {
		pager.setReturnAll(true);
		Map<String, Object> model = new HashMap<String, Object>();
		model.put("key",labelPager(request,modelMap));
		model.put("list", pager.getResultList());
		return new ModelAndView(new ViewExcel(), model);
	}

	@RequestMapping("toLabelManager")
	public String toLabelEditor(HttpServletRequest request,SysLabel sysLabel, ModelMap modelMap){
		/*try {
			sysLabel.setLabel(new String(sysLabel.getLabel().getBytes("iso-8859-1"),"utf-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}*/
		modelMap.put(OBJECT, sysLabel);
		SysLabelSet sysLabelSet = commonService.getSysLabelSet(sysLabel, sysLabel.getLabel());
		if(sysLabelSet!=null) {
			modelMap.put("id", sysLabelSet.getId());
			modelMap.put("adjustCnt", sysLabelSet.getAdjustCnt());
		}else{
			modelMap.put("adjustCnt", 0);
		}
		return "comm/labelManager";
	}
	
	/*
	 * 编辑标签
	 */
	@RequestMapping("manageLabel")
	@ResponseBody
	public Result manageLabel(HttpServletRequest request, @ModelAttribute SysLabel oldSysLabel, @ModelAttribute SysLabelSet sysLabelSet, ModelMap modelMap) throws MyException{
		Result r = new Result();
		String newLabel = request.getParameter("labelNew");
		sysLabelSet.setLabel(newLabel);
		commonService.managerLabel(oldSysLabel, sysLabelSet, newLabel);
		r.setCallbackType(Result.CLOSE_CURRENT);
		r.setNavTabId("listView_"+modelMap.get(FUNID));
		return r;
	}

	/*
	 * 删除标签
	 */
	@RequestMapping("removeLabels")
	@ResponseBody
	public Result removeLabels(HttpServletRequest request,@ModelAttribute SysLabel sysLabel, @ModelAttribute SysLabelSet sysLabelSet, ModelMap modelMap) throws MyException{
		Result r = new Result();
		r.setCallbackType(Result.CLOSE_CURRENT);
		r.setNavTabId("listView_"+modelMap.get(FUNID));
		commonService.removeLabels(sysLabel, sysLabelSet);
		return r;
	}

	@RequestMapping("livePlayer")
	public String livePlayer(HttpServletRequest request, ModelMap modelMap){
		return "comm/livePlayer";
	}
	@RequestMapping("imgShower")
	public String imgShower(HttpServletRequest request, ModelMap modelMap){
		String id = request.getParameter("id");
		String url = request.getParameter("url");
		if(!StringUtils.isEmpty(id)){
			SysAttach attach = (SysAttach)commonService.getEntity(SysAttach.class, Integer.parseInt(id));
			if(attach!=null && !StringUtils.isEmpty(attach.getFilePath())){
				url = attach.getFilePath();
			}
		}
		modelMap.put("url", url);
		return "comm/imgShower";
	}
	

	
//	@RequestMapping("updateLabel")
//	@ResponseBody
//	public Result updateLabel(HttpServletRequest request,@ModelAttribute SysLabel obj, ModelMap modelMap) throws MyException{
//		Result r = new Result();
//		//TODO   commonService.updateLabel(obj);
//		r.setCallbackType(Result.CLOSE_CURRENT);
//		r.setNavTabId("listView_"+modelMap.get(FUNID));
//		return r;
//	}

	
	
	

	//======================================================================================================================================================================
	//审核日志
	//======================================================================================================================================================================
	
	@RequestMapping("approveLogPager")
	public String approveLogPager(HttpServletRequest request, @RequestParam("entityType") String entityType, @RequestParam("entityId") String entityId, ModelMap modelMap){
		pager.getScMap().put("entityType", entityType);
		pager.getScMap().put("entityId", entityId);
		commonService.pagerApproveLog(pager);
		modelMap.put("pager", pager);
		return "comm/approveLogPager";
	}
	

	//======================================================================================================================================================================
	//与项目相关的方法
	//======================================================================================================================================================================
	

	public List<DsRelation> getDsRelationList(HttpServletRequest request, String idName){
		List<DsRelation> list = new ArrayList<DsRelation>();
		Map<String, String> tempMap = new HashMap<String, String>();
		String[] dsEmpId = request.getParameterValues(idName);
		if(dsEmpId!=null && dsEmpId.length>0){
			for(String empId : dsEmpId){
				if(!tempMap.containsKey(empId)){
					tempMap.put(empId, empId);
					list.add(new DsRelation(empId));
				}
			}
		}
		return list;
	}


	public List<GuestRelation> getGuestRelationList(HttpServletRequest request, String prefix){
		List<GuestRelation> list = new ArrayList<GuestRelation>();
		String[] empNames = request.getParameterValues(prefix + "empName");
		String[] dwNames = request.getParameterValues(prefix + "dwName");
		String[] zws = request.getParameterValues(prefix + "zw");
		String[] empDesc = request.getParameterValues(prefix + "empDesc");
		
		if(empNames!=null && empNames.length>0){
			for(int i=0; i<empNames.length; i++){
				GuestRelation guest = new GuestRelation();
				guest.setEmpName(empNames[i]);
				guest.setDwName(dwNames[i]);
				guest.setZw(zws[i]);
				guest.setEmpDesc(empDesc[i]);
				list.add(guest);
			}
		}
		return list;
	}

	@RequestMapping("dsRelationListDiv")
	public String dsRelationListDiv(HttpServletRequest request, 
			@RequestParam("entityType_I") String entityType_I, @RequestParam("entityId_I") String entityId_I,
			ModelMap modelMap){
		
		Pager pager = new Pager();
		pager.setReturnAll(true);
		pager.getScMap().put("entityType_I", entityType_I);
		pager.getScMap().put("entityId_I", entityId_I);
		commonService.pagerDsRelation(null, pager); 
		if("EDIT".equals(todo)||"UPDATE".equals(todo)){
			List<Map<String, Object>> dsRelationList = pager.getResultList();
			modelMap.put("dsRelationList", dsRelationList);
			return "comm/dsRelationListDiv";
		}else{
			modelMap.put("TODO", "INC_PAGER");
			modelMap.put("pager", pager);
			return "ds/dsPager";
		}
	}
	
	

	@RequestMapping("guestRelationListDiv")
	public String guestRelationListDiv(HttpServletRequest request, 
			@RequestParam("entityType_I") String entityType_I, @RequestParam("entityId_I") String entityId_I,
			ModelMap modelMap){
		
		Pager pager = new Pager();
		pager.setReturnAll(true);
		pager.getScMap().put("entityType_I", entityType_I);
		pager.getScMap().put("entityId_I", entityId_I);
		commonService.pagerGuestRelation(null, pager); 
		List<Map<String, Object>> guestRelationList = pager.getResultList();
		modelMap.put("guestRelationList", guestRelationList);
		return "comm/guestRelationListDiv";
	}
	


	/**************************************************************************************************************
	 * 员工联想自动补全  通用查询
	 **************************************************************************************************************/
	@RequestMapping("getEmpList/{type}")
	@ResponseBody
	public List<Map<String, Object>> getEmpList(HttpServletRequest request,
			 @PathVariable("type") String type, ModelMap modelMap) {
		List<Map<String, Object>> r = new ArrayList<Map<String, Object>>();
		try {
			String empName_L = request.getParameter("empName");
			Map<String,String> paramMap = new HashMap<String, String>();
			if(!StringUtils.isEmpty(empName_L)){
				paramMap.put("empName_L", empName_L);
			}
			r = commonService.getEmpList(type, paramMap);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
		return r;
	}
	


	/**************************************************************************************************************
	 * 员工查找带回   通用查询
	 **************************************************************************************************************/
	@RequestMapping("empLookup/{type}")
	public String empLookup(HttpServletRequest request, @PageParam Pager pager,
			@PathVariable("type") String type, ModelMap modelMap) {
		try {
			pager.setNumPerPage(10);
			pager.getScMap().put("activeStatusInt","1");
			commonService.empLookupPager(type, pager);
			pager.setAction(request.getRequestURL() +"?" + request.getQueryString());
			

			modelMap.put("type", type);
			modelMap.put("pager", pager);
			modelMap.put("targetType", "dialog");
			return "ds/empLookup";
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
			return "msg/common/fail";
		}
	}
	



	/**************************************************************************************************************
	 * 组织联想自动补全  通用查询
	 **************************************************************************************************************/
	@RequestMapping("getOrgList/{type}")
	@ResponseBody
	public List<Map<String, Object>> getOrgList(HttpServletRequest request,
			 @PathVariable("type") String type, ModelMap modelMap) {
		List<Map<String, Object>> r = new ArrayList<Map<String, Object>>();
		try {
			String orgName_L = request.getParameter("orgName");
			Map<String,String> paramMap = new HashMap<String, String>();
			if(!StringUtils.isEmpty(orgName_L)){
				paramMap.put("orgName_L", orgName_L);
			}
			r = commonService.getOrgList(type, paramMap);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
		return r;
	}
	


	/**************************************************************************************************************
	 * 组织查找带回 通用查询
	 **************************************************************************************************************/
	@RequestMapping("orgLookup/{type}")
	public String orgLookup(HttpServletRequest request, @PageParam Pager pager,
			@PathVariable("type") String type, ModelMap modelMap) {
		try {
			pager.setNumPerPage(10);
			pager.getScMap().put("activeStatusInt","1");
			commonService.orgLookupPager(type, pager);
			pager.setAction(request.getRequestURL() +"?" + request.getQueryString());
			

			modelMap.put("type", type);
			modelMap.put("pager", pager);
			modelMap.put("targetType", "dialog");
			return "ds/empLookup";
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
			return "msg/common/fail";
		}
	}

	/**
	 * 更改可用状态
	 * @return
	 */
	@RequestMapping("/updateStatus")
	@ResponseBody
	public Result updateStatus(@RequestParam(value = "userType",required = false) String userType,
							   @RequestParam(value = "id",required = false) Integer id,
							   @RequestParam(value = "status",required = false)Integer status){
		Result result = new Result();
		result.setCallbackType("");
		BaseEmp emp = null;
		String url= "";
		if(userType.equals("DsEmp")){
			emp = (BaseEmp) commonService.getEntity(DsEmp.class,id);
		}else if(userType.equals("CyzjEmp")){
			emp = (BaseEmp) commonService.getEntity(CyzjEmp.class,id);
		}else if(userType.equals("ZdzxEmp")){
			emp = (BaseEmp) commonService.getEntity(ZdzxEmp.class,id);
		}
		emp.setActiveStatusInt(status);
		try {
			commonService.edit(emp);
		} catch (MyException e) {
			e.printStackTrace();
		}
		return result;
	}
}
